package fr.ul.ade.secunde.ui;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import fr.ul.ade.R;
import fr.ul.ade.secunde.database.AdeWebContract;
import fr.ul.ade.secunde.util.Bundles;
import fr.ul.ade.secunde.util.ResourceManager;
import fr.ul.ade.secunde.util.UiUtils;

/**
 * Fragment contenant le formulaire d'édition d'un emploi du temps.
 * 
 * @author Michaël Schnell
 * @since Jul 2, 2013
 * 
 * @version 1.7
 */
public class EditScheduleFragment
		extends CreateScheduleFragment {

	/**
	 * Identifiant de l'emploi du temps affiché.
	 */
	protected long scheduleId;

	public static EditScheduleFragment newInstance(long scheduleId) {
		final EditScheduleFragment fragment = new EditScheduleFragment();
		Bundle args = new Bundle();
		args.putLong(Bundles.SCHEDULE_ID, scheduleId);
		fragment.setArguments(args);
		return fragment;
	}

	// --------------------------------------------------------
	//
	// Création
	//
	// --------------------------------------------------------

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		Bundle args = this.getArguments();
		// Dans le cas d'un mobile, l'identifiant de l'emploi du temps est passé
		// par l'intent.
		if (args == null || !args.containsKey(Bundles.SCHEDULE_ID)) {
			this.scheduleId = this.getActivity().getIntent()
					.getLongExtra(Bundles.SCHEDULE_ID, 0);
		} else {
			this.scheduleId = args.getLong(Bundles.SCHEDULE_ID);
		}
	}

	/**
	 * Construit et retourne l'écouteur pour le bouton d'enregistrement.
	 * 
	 * @return {@link OnClickListener} pour le bouton d'enregistrement
	 */
	@Override
	protected OnClickListener getSaveListener() {
		return new EditScheduleListener(this);
	}

	// --------------------------------------------------------
	//
	// Traitement des données
	//
	// --------------------------------------------------------

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		if (id == ScheduleQuery._TOKEN) {
			Uri projectUri = AdeWebContract.Schedule.buildUri(this.scheduleId);
			String[] projection = ScheduleQuery.PROJECTION;
			String selection = null;
			String[] selectionArgs = null;

			return new CursorLoader(this.getActivity(), projectUri, projection,
					selection, selectionArgs,
					AdeWebContract.Schedule.DEFAULT_SORT);
		}
		return super.onCreateLoader(id, args);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		/* Nothing to be done. */
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		if (this.getActivity() == null) {
			return;
		}// if

		if (!data.moveToFirst()) {
			// IMP Review log messages
			Log.d("EditScheduleFragment", "Invalid schedule id: "
					+ this.scheduleId);
			return;
		}

		if (loader.getId() == ScheduleQuery._TOKEN) {
			this.fillForm(data);
		} else { /* loader.getId() == ProjectQuery._TOKEN */
			super.onLoadFinished(loader, data);
			// On commence le chargement de l'edt qu'une fois les projets
			// chargés pour éviter que le chargment de l'edt ne se termine avant
			// le chargement des projets (sinon, on ne peut pas correctement
			// initialiser le spinner des projets)
			this.getLoaderManager()
					.initLoader(ScheduleQuery._TOKEN, null, this);
		}
	}

	protected void fillForm(Cursor scheduleValues) {
		final View form = this.getView();

		UiUtils.setTextViewContent(form,
				R.id.create_schedule_name,
				scheduleValues.getString(ScheduleQuery.SCHEDULE_NAME));

		UiUtils.setTextViewContent(form,
				R.id.create_schedule_description,
				scheduleValues.getString(ScheduleQuery.SCHEDULE_DESCRIPTION));

		for (String resource : ResourceManager.splitResources(scheduleValues
				.getString(ScheduleQuery.SCHEDULE_RESOURCES))) {
			if (!TextUtils.isEmpty(resource)) {
				this.addResource(resource);
			}
		}
		for (String studentNumber : ResourceManager
				.splitResources(scheduleValues
						.getString(ScheduleQuery.SCHEDULE_STUDENT_NUM))) {
			if (!TextUtils.isEmpty(studentNumber)) {
				this.addResource(studentNumber);
			}
		}

		UiUtils.setSpinnerSelection(form,
				R.id.create_schedule_period_spinner,
				scheduleValues.getString(ScheduleQuery.SCHEDULE_PERIOD));

		UiUtils.setSpinnerSelection(form,
				R.id.create_schedule_project_spinner,
				Long.valueOf(scheduleValues
						.getLong(ScheduleQuery.SCHEDULE_PROJECT)));
	}

	// --------------------------------------------------------
	//
	// Données chargées
	//
	// --------------------------------------------------------

	protected interface ScheduleQuery {
		final int _TOKEN = 0x2;

		final String[] PROJECTION = { BaseColumns._ID,
				AdeWebContract.Schedule.SCHEDULE_NAME,
				AdeWebContract.Schedule.SCHEDULE_DESCRIPTION,
				AdeWebContract.Schedule.SCHEDULE_PERIOD,
				AdeWebContract.Schedule.SCHEDULE_PROJECT,
				AdeWebContract.Schedule.SCHEDULE_RESOURCES,
				AdeWebContract.Schedule.SCHEDULE_STUDENT_NUM };

		final int _ID = 0;
		final int SCHEDULE_NAME = 1;
		final int SCHEDULE_DESCRIPTION = 2;
		final int SCHEDULE_PERIOD = 3;
		final int SCHEDULE_PROJECT = 4;
		final int SCHEDULE_RESOURCES = 5;
		final int SCHEDULE_STUDENT_NUM = 6;
	}

	// --------------------------------------------------------
	//
	// Edition de l'emploi du temps
	//
	// --------------------------------------------------------

	/**
	 * Ecouteur qui lance la création d'un emploi du temps à partir des valeurs
	 * recupérées dans le formulaire.
	 * 
	 * @author Michaël Schnell
	 * @since Jul 8, 2013
	 * 
	 * @version 1.3
	 */
	private static class EditScheduleListener
			implements OnClickListener {

		private EditScheduleFragment fragment;

		public EditScheduleListener(EditScheduleFragment fragment) {
			this.fragment = fragment;
		}

		@Override
		public void onClick(View v) {
			ScheduleValues scheduleValues = this.fragment
					.retrieveScheduleValues();
			ContentValues values = scheduleValues.getContent();
			Log.d("[onEdit]", values.toString());

			this.fragment
					.getActivity()
					.getContentResolver()
					.update(AdeWebContract.Schedule.buildUri(this.fragment.scheduleId),
							values,
							null,
							null);
			this.fragment.getActivity().onBackPressed();
		}

	}// class EditScheduleListener

}// class EditScheduleFragment